package com.zhangsun.springShiro.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhangsun.springShiro.common.constant.Constant;
import com.zhangsun.springShiro.system.bean.TheUser;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        TheUser theUser = (TheUser) SecurityUtils.getSubject().getPrincipal();
        String userId = Constant.ADMIN_USER_ID;
        if (theUser != null) {
            userId = theUser.getUserId();
        }
        this.setInsertFieldValByName("createUser", userId, metaObject);
        this.setInsertFieldValByName("createTime", new Date(), metaObject);
        this.setInsertFieldValByName("modifyUser", userId, metaObject);
        this.setInsertFieldValByName("modifyTime", new Date(), metaObject);
    }

    /**
     * 更新
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        TheUser theUser = (TheUser) SecurityUtils.getSubject().getPrincipal();
        String userId = Constant.ADMIN_USER_ID;
        if (theUser != null) {
            userId = theUser.getUserId();
        }
        this.setInsertFieldValByName("modifyUser", userId, metaObject);
        this.setUpdateFieldValByName("modifyTime", new Date(), metaObject);
    }
}
